<!DOCTYPE html>
<html>
<head>
    <title>WebSocket 实时更新</title>
</head>
<body>
    <h1>实时更新的消息：</h1>
    <div id="messages"></div>

    <script>
        // 创建 WebSocket 连接
        var socket = new WebSocket("ws://localhost:8080/websocket");

        // 连接成功时触发
        socket.onopen = function(event) {
            console.log("WebSocket 连接成功");
        };

        // 接收到消息时触发
        socket.onmessage = function(event) {
            var messagesDiv = document.getElementById("messages");
            var newMessage = document.createElement("p");
            newMessage.textContent = "新消息: " + event.data;
            messagesDiv.appendChild(newMessage);
        };

        // 连接关闭时触发
        socket.onclose = function(event) {
            console.log("WebSocket 连接关闭");
        };

        // 连接错误时触发
        socket.onerror = function(error) {
            console.log("WebSocket 错误: " + error.message);
        };
    </script>
</body>
</html>
